<template>
  <div class="item-search">
    <NavBar title="搜索" back/>
    <van-search placeholder="汽车用品" v-model="goodsName" v-on:input="searchByGoodsName" show-action @search="searchByGoodsName" style="background: #fafafa;">
      <div slot="action" @click="searchClickByGoodsName">搜索</div>
    </van-search>
    <van-cell-group v-for="(item, index) in itemList" v-bind:key="index">
      <a @click="toGoodsDetail(item.goodsId)">
        <van-cell :title='item.name'/>
      </a>
    </van-cell-group>
    <div class="hotSearch" v-if="isShowHotTag">
      <h2 class="hot-search">热门搜索</h2>
      <van-cell-group v-for="(tag, index) in tagList" v-bind:key="index">
        <a @click="clickHotTag(tag.tag)">
          <van-cell :title='tag.tag'/>
        </a>
      </van-cell-group>
    </div>
  </div>
</template>
<script>
import NavBar from '../../components/common/NavBar.vue'
import Vue from 'vue'
import { Toast } from 'vant'
import searchApi from '../../api/search'
Vue.use(Toast)
export default {
  name: 'itemSearch',
  data () {
    return {
      goodsName: '',
      tagList: [],
      itemList: [],
      isShowHotTag: true
    }
  },
  components: {
    NavBar
  },
  watch: {
    itemList (oldList, newList) {
      if (newList.length > 0 || oldList.length > 0) {
        this.isShowHotTag = false
      } else {
        this.isShowHotTag = true
      }
    }
  },
  methods: {
    // 获取后台的热门标签
    selectHotTag: function () {
      const _this = this
      searchApi.selectHotTag().then(function (res) {
        _this.tagList = res.data.re
      })
    },
    // 将选中的标签直接去查询
    clickHotTag: function (tag) {
      this.$router.push({path: 'item/searchItemList', query: {goodsName: tag}})
    },
    // 跳转到商品详情页
    toGoodsDetail: function (_goodsId) {
      this.$router.push({path: 'item/detail', query: {goodsId: _goodsId}})
    },
    // 及时联想查询
    searchByGoodsName: function () {
      const _this = this
      _this.itemList = []
      searchApi.searchByGoodsName(_this.goodsName).then(function (res) {
        if (res.data.re.dataList.length > 0) {
          _this.itemList = res.data.re.dataList
        }
      })
    },
    // 及时联想查询
    searchClickByGoodsName: function () {
      if (this.goodsName === '') {
        Toast.fail('搜索数据不能为空！')
      } else {
        this.$router.push({path: 'item/searchItemList', query: {goodsName: this.goodsName}})
      }
    }
  },
  mounted () {
    this.selectHotTag()
  }
}
</script>
<style>
  .item-search {
    background: #fff;
    height: 100%;
  }
  .hotSearch .van-cell {
    padding: 5px 15px;
  }
  .hotSearch .van-cell__title {
    font-size: 12px;
  }
  .hotSearch .hot-search {
    margin: 0;
    font-size: 14px;
    padding: 15px;
    font-weight: 600;
  }

</style>
